#!/usr/bin/bash
set -euo pipefail

IGNITION_RESULT=/etc/.ignition-result.json

WARN='\033[0;33m' # yellow
RESET='\033[0m' # reset

mkdir -p /run/issue.d
touch /run/issue.d/30_coreos_ignition_provisioning.issue

d=$(date --date "$(jq -r .provisioningDate "${IGNITION_RESULT}")" +"%Y/%m/%d %H:%M:%S %Z")
ignitionBoot=$(jq -r .provisioningBootID "${IGNITION_RESULT}")
if [ $(cat /proc/sys/kernel/random/boot_id) = "${ignitionBoot}" ]; then
    echo "Ignition: ran on ${d} (this boot)" \
        > /run/issue.d/30_coreos_ignition_provisioning.issue

    # checking for /run/ostree-live as the live system with persistent storage can run Ignition more than once
    if ! test -f /run/ostree-live && jq -e .previousReport.provisioningDate "${IGNITION_RESULT}" &>/dev/null; then
        prevdate=$(date --date "$(jq -r .previousReport.provisioningDate "${IGNITION_RESULT}")" +"%Y/%m/%d %H:%M:%S %Z")
        cat << EOF > /etc/issue.d/30_coreos_ignition_run_more_than_once.issue
${WARN}
############################################################################
WARNING: Ignition previously ran on ${prevdate}. Unexpected 
behavior may occur. Ignition is not designed to run more than once per system.
############################################################################
${RESET}
EOF
    fi
else
    nreboots=$(($(journalctl --list-boots | wc -l) - 1))
    [ "${nreboots}" -eq 1 ] && boot="boot" || boot="boots"
    echo "Ignition: ran on ${d} (at least $nreboots $boot ago)" \
        > /run/issue.d/30_coreos_ignition_provisioning.issue
fi

if jq -e .userConfigProvided "${IGNITION_RESULT}" &>/dev/null; then
    echo "Ignition: user-provided config was applied" \
        >> /run/issue.d/30_coreos_ignition_provisioning.issue
else
    echo -e "${WARN}Ignition: no config provided by user${RESET}" \
        >> /run/issue.d/30_coreos_ignition_provisioning.issue
fi

# Our makeshift way of getting /run/issue.d semantics. See:
# https://github.com/coreos/console-login-helper-messages/blob/e06fc88ae8fbcc3a422bc8c686f70c15aebb9d9a/usr/lib/console-login-helper-messages/issue.defs#L8-L17
ln -sf /run/issue.d/30_coreos_ignition_provisioning.issue /etc/issue.d/
